package com.example.task;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.config.RedisCache;
import com.example.entity.dto.pc.GetProductLineMachineHzViewDto;
import com.example.entity.hz.MOCTA;
import com.example.entity.hz.SFCTA;
import com.example.entity.mysql.Productprocessresource;
import com.example.entity.mysql.Workresource;
import com.example.entity.vo.hzView.HzCmsmxView;
import com.example.entity.vo.hzView.HzMoctaView;
import com.example.entity.vo.hzView.HzSfctaView;
import com.example.entity.yifei.Cmsmv;
import com.example.entity.yifei.Mocta2;
import com.example.entity.yifei.Mocty;
import com.example.entity.yifei.Tablesynclog;
import com.example.enums.MOCStatusEnum;
import com.example.mapper.*;
import com.example.mapper.hzViewSync.HzViewSyncMapper;
import com.example.mapper.pc.ProductprocessresourceMapper;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.ResourcegroupMapper;
import com.example.service.*;
import com.example.service.pc.ProductprocessresourceService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.service.pc.WorkresourceService;
import com.example.untils.BeanUtils;
import com.example.untils.LanguageConversionUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
@Order(Integer.MAX_VALUE)
@Slf4j
public class RedisTask {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ResourcegroupService resourcegroupService;

    @Autowired
    private ViewsynclogService viewsynclogService;
    @Autowired
    private WorkresourceService workresourceService;
    @Autowired
    private HzViewSyncMapper hzViewSyncMapper;
    @Autowired
    private ResourcegroupMapper resourcegroupMapper;
    @Autowired
    private ProductprocessresourceService productprocessresourceService;
    @Autowired
    private ProductprocessresourceMapper productprocessresourceMapper;
    @Autowired
    private TablesynclogService tablesynclogService;
    @Autowired
    private InvmbMapper invmbMapper;
    @Autowired
    private InvmbService invmbService;
    @Autowired
    private CmsmeMapper cmsmeMapper;
    @Autowired
    private CmsmvMapper cmsmvMapper;
    @Autowired
    private CmsmeService cmsmeService;
    @Autowired
    private CmsmvService cmsmvService;
    @Autowired
    private CmsmcMapper cmsmcMapper;
    @Autowired
    private CmsmcService cmsmcService;
    @Autowired
    private BommfMapper bommfMapper;
    @Autowired
    private BommfService bommfService;
    @Autowired
    private CmsmdService cmsmdService;
    @Autowired
    private CmsmdMapper cmsmdMapper;
    @Autowired
    private PurmaService purmaService;
    @Autowired
    private PurmaMapper purmaMapper;
    @Autowired
    private BommeMapper bommeMapper;
    @Autowired
    private BommeService bommeService;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private CoptdMapper coptdMapper;
    @Autowired
    private CoptdService coptdService;
    @Autowired
    private PurcdMapper purcdMapper;
    @Autowired
    private PurcdService purcdService;
    @Autowired
    private PurtdMapper purtdMapper;
    @Autowired
    private PurtdService purtdService;
    @Autowired
    private MoctaMapper moctaMapper;
    @Autowired
    private MoctaService moctaService;
    @Autowired
    private SfctaMapper sfctaMapper;
    @Autowired
    private SfctaService sfctaService;
    @Autowired
    private MoctbService moctbService;
    @Autowired
    private MoctbMapper moctbMapper;
    @Autowired
    private MoctyService moctyService;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private Mocta2Mapper mocta2Mapper;
    @Autowired
    private Mocta2Service mocta2Service;
    @Autowired
    private Moctb2Mapper moctb2Mapper;
    @Autowired
    private Moctb2Service moctb2Service;
    @Autowired
    private MocteMapper mocteMapper;
    @Autowired
    private MocteService mocteService;
    @Autowired
    private MoctgMapper moctgMapper;
    @Autowired
    private MoctgService moctgService;

    @Value("${spring.profiles.active}")
    private String active;


//    @Scheduled(cron = "0 0/5 * * * ?")
//    public void resourceGroupList() {
//        List<Resourcegroup> groups = resourcegroupService.list();
//        redisCache.deleteObject("resourceGroupList");
//        redisCache.setCacheList("resourceGroupList", groups);
//    }

    @Scheduled(cron = "0 0/20 * * * ?")
    @DSTransactional
    public void mocta_sfctaViewSync() {
        System.out.println("active = " + active);
        if(!"hz".equals(active)) {
            return;
        }
        System.out.println("SFCTASync....." + TimeUtils.getFullNowTime());
        Tablesynclog sfctaLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "SFCTA"));
        List<HzSfctaView> sfctaViewList = null;
        if(sfctaLog == null || StringUtils.isEmpty(sfctaLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            sfctaViewList = hzViewSyncMapper.hzSfctaViewList(null);
        }else{
            sfctaViewList = hzViewSyncMapper.hzSfctaViewList(sfctaLog.getLastsynctime());
        }
        if(sfctaViewList != null && sfctaViewList.size() > 0) {

            List<String> sfctaKeyList = sfctaMapper.getSfctaKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : sfctaKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzSfctaView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < sfctaViewList.size(); i++) {
                sfctaViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(sfctaViewList.get(i)));
            }
            for(HzSfctaView item : sfctaViewList) {
                viewMap.put(item.getTA001().trim() + "^" + item.getTA002().trim() + "^" + item.getTA003().trim(), item);
                viewSet.add(item.getTA001().trim() + "^" + item.getTA002().trim() + "^" + item.getTA003().trim());
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);
            List<SFCTA> insSfctaList = new ArrayList<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzSfctaView view = viewMap.get(t);
                SFCTA sfcta = new SFCTA();
                BeanUtils.copyPropertiesIgnoreCase(view, sfcta);
                insSfctaList.add(sfcta);
            }
            // 批量插入
            sfctaService.saveBatch(insSfctaList);
            if(sfctaLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("SFCTA");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "SFCTA"));
            }
        }
        System.out.println("SFCTA end....." + TimeUtils.getFullNowTime());

        System.out.println("原MOCTA Sync....." + TimeUtils.getFullNowTime());
        Tablesynclog moctaLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTA"));
        List<HzMoctaView> moctaViewList = null;
        if(moctaLog == null || StringUtils.isEmpty(moctaLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            moctaViewList = hzViewSyncMapper.hzMoctaViewList(null);
        }else{
            moctaViewList = hzViewSyncMapper.hzMoctaViewList(moctaLog.getLastsynctime());
        }
        if(moctaViewList != null && moctaViewList.size() > 0) {

            List<Cmsmv> cmsmvList = cmsmvMapper.selectList(null);
            Map<String, String> cmsmvMap = new HashMap<>();
            for(Cmsmv cmsmv : cmsmvList) {
                cmsmvMap.put(cmsmv.getMv002().trim(), cmsmv.getMv001().trim());
            }

            List<String> moctaKeyList = moctaMapper.getmocta2KeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : moctaKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMoctaView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < moctaViewList.size(); i++) {
                moctaViewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(moctaViewList.get(i)));
            }
            for(HzMoctaView item : moctaViewList) {
                viewMap.put(item.getTA001().trim() + "^" + item.getTA002().trim(), item);
                viewSet.add(item.getTA001().trim() + "^" + item.getTA002().trim());
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);
            List<Mocta2> insMoctaList = new ArrayList<>();
            List<Mocty> insMoctyList = new ArrayList<>();
            List<Workresource> insWorkresourceList = new ArrayList<>();
            // 存一下每一个资源组的工作时间
            Map<String, BigDecimal> hzCmsmxMap = new HashMap<>();
            List<HzCmsmxView> hzCmsmxViewList = hzViewSyncMapper.hzCmsmxViewList();
            for(HzCmsmxView t : hzCmsmxViewList) {
                if(t.getResourceType().equals(1)) {
                    hzCmsmxMap.put(t.getMX009().trim(), t.getMX004());
                }else if(t.getResourceType().equals(2)) {
                    hzCmsmxMap.put(t.getMX009().trim(), t.getMX004());
                }
            }

            for(String t : cp) {  // 插入VIEW中多的
                HzMoctaView view = viewMap.get(t);
                Mocta2 mocta = new Mocta2();
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setCREATOR("ERP");
                mocta.setCREATE_DATE(TimeUtils.getNowTime());
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                insMoctaList.add(mocta);

                String uuid = UUID.randomUUID().toString();
                int productNumPerDay = 0;
                // 如果有产能的，需要算机器每日的产能。   如果没有的话，则直接排满
                List<SFCTA> sfctaList = sfctaMapper.selectList(new LambdaQueryWrapper<SFCTA>()
                        .eq(SFCTA::getTA001, view.getTA001().trim()).eq(SFCTA::getTA002, view.getTA025TA006().trim()).orderByAsc(SFCTA::getTA003));
                if(sfctaList == null || sfctaList.size() == 0) {
                    log.info(view.getTA001().trim() + " , " + view.getTA025TA006() + " no sfcta data...");
                    continue;
                }
                SFCTA sfcta = sfctaList.get(0);
                List<Productprocessresource> list = productprocessresourceMapper.selPPRListHzVersion(
                        new GetProductLineMachineHzViewDto(mocta.getTA006(), sfcta.getTA003(), sfcta.getTA004(), mocta.getUDF01(),
                                mocta.getUDF02(), mocta.getTA021(), mocta.getUDF04(), null, 1));
                boolean flag = false;
                Integer jutiId = null;
                for(Productprocessresource productprocessresource : list) {
                    if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                        // 如果是装配车间的话，不需要填充 1和2 之外的东西
                        if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                            continue;
                        }
                    }
                    if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {   // 看一下这个工单能不能选到具体的 生产线/设备
                        List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                        if(idList == null || idList.size() == 0) continue;
                        if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                            jutiId = idList.get(0);
                        }
                        BigDecimal hours = hzCmsmxMap.get(productprocessresource.getResourceGroupNO().trim());
                        double v = hours.doubleValue();
                        productNumPerDay = (int) Math.floor(v * 3600 / productprocessresource.getBeat());  // 计算日产量
                        flag = true;  break;
                    }
                }
                if(!flag) {  // 如果没有绑定生产线/设备

                    Mocty mocty = new Mocty();
                    mocty.setCreator("ERP"); mocty.setCreateDate(TimeUtils.getNowTime());
                    mocty.setTy001(view.getTA001().trim());
                    mocty.setTy002(view.getTA025TA006().trim());
                    mocty.setTy003(view.getTA009().trim());
                    mocty.setTy004(view.getTA015().doubleValue());
                    mocty.setTy009("****");  mocty.setTy019(sfcta.getTA003());  // 工序
                    mocty.setUdf05(UUID.randomUUID().toString());
                    mocty.setUdf06(uuid);
                    mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
                    mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
                    mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                    mocty.setUdf04("转入参数: " + view.toString());
                    insMoctyList.add(mocty);
                    for(Productprocessresource productprocessresource : list) {
                        if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                            // 如果是装配车间的话，不需要填充 1和2 之外的东西
                            if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                                continue;
                            }
                        }
                        Workresource workresource = new Workresource();
                        workresource.setWorkResourceId(UUID.randomUUID().toString());
                        workresource.setWorkSingle(mocta.getTA001());
                        workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
                        workresource.setProcessNo(sfcta.getTA003());
                        workresource.setProcessId(sfcta.getTA004());
                        workresource.setResourceGroupId(productprocessresource.getResourceGroupId());
                        if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
                            List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                            if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                workresource.setResourceId(idList.get(0));
                            }
                        }else{
                            List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
                            if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                workresource.setResourceId(idList.get(0));
                            }
                        }
                        workresource.setDate(mocta.getTA009());
                        workresource.setBeat(productprocessresource.getBeat());
                        workresource.setQuota(productprocessresource.getQuota());
                        workresource.setCreator("ERP");
                        workresource.setCreateTime(TimeUtils.getFullNowTime());
                        workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
                        workresource.setPeopleNum(1);
                        workresource.setResourceTypeId(productprocessresource.getResourceTypeId());
                        insWorkresourceList.add(workresource);
                    }
                }else{
                    int day = (int) Math.ceil(mocta.getTA015().doubleValue() / productNumPerDay);
                    int sum = 0;
                    // 需要查看当天是否为休息日，如果是的话，则需要往后排
                    for(int i = 0; i < day; i++) {
                        Mocty mocty = new Mocty();
                        mocty.setCreator("ERP"); mocty.setCreateDate(TimeUtils.getNowTime());
                        mocty.setTy001(view.getTA001().trim());
                        mocty.setTy002(view.getTA025TA006().trim());
                        mocty.setTy003(TimeUtils.addOrSubtract(view.getTA009().trim(), i));
                        if(i == day - 1) mocty.setTy004(mocta.getTA015().doubleValue() - sum);
                        else {
                            sum += productNumPerDay;
                            mocty.setTy004(new Double(productNumPerDay));
                        }
                        if(jutiId == null) {
                            mocty.setTy009("****");
                            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                        }
                        else {
                            mocty.setTy009(jutiId.toString());
                            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                        }
                        mocty.setTy019(sfcta.getTA003());  // 工序
                        mocty.setUdf05(UUID.randomUUID().toString());
                        mocty.setUdf06(uuid);
                        mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
                        mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
                        mocty.setUdf04("转入参数: " + view.toString());
                        insMoctyList.add(mocty);
                        for(Productprocessresource productprocessresource : list) {
                            if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                                // 如果是装配车间的话，不需要填充 1和2 之外的东西
                                if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                                    continue;
                                }
                            }
                            Workresource workresource = new Workresource();
                            workresource.setWorkResourceId(UUID.randomUUID().toString());
                            workresource.setWorkSingle(mocta.getTA001());
                            workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
                            workresource.setProcessNo(sfcta.getTA003());
                            workresource.setProcessId(sfcta.getTA004());
                            workresource.setResourceGroupId(productprocessresource.getResourceGroupId());

                            if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                                if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                    workresource.setResourceId(idList.get(0));
                                }
                            }else{
                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
                                if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                    workresource.setResourceId(idList.get(0));
                                }
                            }
                            workresource.setDate(TimeUtils.addOrSubtract(mocta.getTA009().trim(), i));
                            workresource.setBeat(productprocessresource.getBeat());
                            workresource.setQuota(productprocessresource.getQuota());
                            workresource.setCreator("ERP");
                            workresource.setCreateTime(TimeUtils.getFullNowTime());
                            workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
                            workresource.setPeopleNum(1);
                            workresource.setResourceTypeId(productprocessresource.getResourceTypeId());
                            insWorkresourceList.add(workresource);
                        }
                    }
                }
            }
            // 批量插入
            mocta2Service.saveBatch(insMoctaList);
            moctyService.saveBatch(insMoctyList);
            workresourceService.saveBatch(insWorkresourceList);

            cp  = new HashSet<>(originSet);
            cp.retainAll(viewSet);
            for(String t : cp) {
                Mocta2 mocta = new Mocta2();
                HzMoctaView view = viewMap.get(t);
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setMODIFIER("ERP");
                mocta.setMODI_DATE(TimeUtils.getNowTime());
                Mocta2 originData = mocta2Service.getOne(new LambdaQueryWrapper<Mocta2>().eq(Mocta2::getTA001, view.getTA001()).eq(Mocta2::getTA002, view.getTA002()));
                mocta2Service.update(mocta, new LambdaQueryWrapper<Mocta2>().eq(Mocta2::getTA001, view.getTA001()).eq(Mocta2::getTA002, view.getTA002()));

                if((!originData.getTA009().trim().equals(view.getTA009().trim()) || !originData.getTA015().equals(view.getTA015()))) {   // 如果排产日期不相等 || 如果数量不相等
                    List<Mocty> needRemoveList = moctyMapper.selectList(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf11, originData.getTA001()).eq(Mocty::getUdf12, originData.getTA002()));
                    for(Mocty needRemoveMocty : needRemoveList) {
                        moctyService.remove(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf11, originData.getTA001()).eq(Mocty::getUdf12, originData.getTA002()));
                        workresourceService.remove(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, needRemoveMocty.getUdf05()));
                    }

                    String uuid = UUID.randomUUID().toString();
                    int productNumPerDay = 0;
                    // 如果有产能的，需要算机器每日的产能。   如果没有的话，则直接排满
//                    SFCTA sfcta = sfctaMapper.selectOne(new LambdaQueryWrapper<SFCTA>()
//                            .eq(SFCTA::getTA001, view.getTA001().trim()).eq(SFCTA::getTA002, view.getTA025TA006().trim()).eq(SFCTA::getTA003, "0010"));
//                    if(sfcta == null) {
//                        System.out.println(view.getTA001().trim() + " , " + view.getTA025TA006() + " no sfcta data...");
//                        continue;
//                    }
                    List<SFCTA> sfctaList = sfctaMapper.selectList(new LambdaQueryWrapper<SFCTA>()
                            .eq(SFCTA::getTA001, view.getTA001().trim()).eq(SFCTA::getTA002, view.getTA025TA006().trim())
                            .orderByAsc(SFCTA::getTA003));
                    if(sfctaList == null || sfctaList.size() == 0) {
                        log.info(view.getTA001().trim() + " , " + view.getTA025TA006() + " no sfcta data...");
                        continue;
                    }
                    // 装配线新增的小工序，不能比原先的小。
                    SFCTA sfcta = sfctaList.get(0);
                    List<Productprocessresource> list = productprocessresourceMapper.selPPRListHzVersion(
                            new GetProductLineMachineHzViewDto(mocta.getTA006(), sfcta.getTA003(), sfcta.getTA004(), mocta.getUDF01(),
                                    mocta.getUDF02(), mocta.getTA021(), mocta.getUDF04(), null, 1));
                    boolean flag = false;
                    Integer jutiId = null;
                    for(Productprocessresource productprocessresource : list) {
                        if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                            // 如果是装配车间的话，不需要填充 1和2 之外的东西
                            if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                                continue;
                            }
                        }
                        if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
                            List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                            if(idList == null || idList.size() == 0) continue;
                            if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                jutiId = idList.get(0);
                            }
                            BigDecimal hours = hzCmsmxMap.get(productprocessresource.getResourceGroupNO().trim());
                            double v = hours.doubleValue();
                            productNumPerDay = (int) Math.floor(v * 3600 / productprocessresource.getBeat());
                            flag = true;  break;
                        }
                    }
                    if(!flag) {  // 如果没有绑定生产线/设备
                        Mocty mocty = new Mocty();
                        mocty.setCreator("ERP"); mocty.setCreateDate(TimeUtils.getNowTime());
                        mocty.setTy001(view.getTA001().trim());
                        mocty.setTy002(view.getTA025TA006().trim());
                        mocty.setTy003(view.getTA009().trim());
                        mocty.setTy004(view.getTA015().doubleValue());
                        mocty.setTy009("****");  mocty.setTy019(sfcta.getTA003());  // 工序
                        mocty.setUdf05(UUID.randomUUID().toString());
                        mocty.setUdf06(uuid);
                        mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
                        mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
                        mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                        mocty.setUdf04("转入参数: " + view.toString());
                        moctyMapper.insert(mocty);
                        for(Productprocessresource productprocessresource : list) {
                            if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                                // 如果是装配车间的话，不需要填充 1和2 之外的东西
                                if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                                    continue;
                                }
                            }
                            Workresource workresource = new Workresource();
                            workresource.setWorkResourceId(UUID.randomUUID().toString());
                            workresource.setWorkSingle(mocta.getTA001());
                            workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
                            workresource.setProcessNo(sfcta.getTA003());
                            workresource.setProcessId(sfcta.getTA004());
                            workresource.setResourceGroupId(productprocessresource.getResourceGroupId());

                            if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                                if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                    workresource.setResourceId(idList.get(0));
                                }
                            }else{
                                List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
                                if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                    workresource.setResourceId(idList.get(0));
                                }
                            }
                            workresource.setDate(mocta.getTA009());
                            workresource.setBeat(productprocessresource.getBeat());
                            workresource.setQuota(productprocessresource.getQuota());
                            workresource.setCreator("ERP");
                            workresource.setCreateTime(TimeUtils.getFullNowTime());
                            workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
                            workresource.setPeopleNum(1);
                            workresource.setResourceTypeId(productprocessresource.getResourceTypeId());
                            workresourceService.save(workresource);
                        }
                    }else{
                        int day = (int) Math.ceil(mocta.getTA015().doubleValue() / productNumPerDay);
                        int sum = 0;
                        // 需要查看当天是否为休息日，如果是的话，则需要往后排
                        for(int i = 0; i < day; i++) {
                            Mocty mocty = new Mocty();
                            mocty.setCreator("ERP"); mocty.setCreateDate(TimeUtils.getNowTime());
                            mocty.setTy001(view.getTA001().trim());
                            mocty.setTy002(view.getTA025TA006().trim());
                            mocty.setTy003(TimeUtils.addOrSubtract(view.getTA009().trim(), i));
                            if(i == day - 1) mocty.setTy004(mocta.getTA015().doubleValue() - sum);
                            else {
                                sum += productNumPerDay;
                                mocty.setTy004(new Double(productNumPerDay));
                            }
                            if(jutiId == null) {
                                mocty.setTy009("****");
                                mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                            }
                            else {
                                mocty.setTy009(jutiId.toString());
                                mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                            }
                            mocty.setTy019(sfcta.getTA003());  // 工序
                            mocty.setUdf05(UUID.randomUUID().toString());
                            mocty.setUdf06(uuid);
                            mocty.setUdf11(view.getTA001().trim());  // 原MOCTA TA001
                            mocty.setUdf12(view.getTA002().trim());  // 原MOCTA TA002
                            mocty.setUdf04("转入参数: " + view.toString());
                            moctyMapper.insert(mocty);
                            for(Productprocessresource productprocessresource : list) {
                                if("ST4".equals(mocta.getTA021().trim()) || "ST6".equals(mocta.getTA021().trim())) {
                                    // 如果是装配车间的话，不需要填充 1和2 之外的东西
                                    if(!productprocessresource.getResourceTypeId().equals(1) && !productprocessresource.getResourceTypeId().equals(2)) {
                                        continue;
                                    }
                                }
                                Workresource workresource = new Workresource();
                                workresource.setWorkResourceId(UUID.randomUUID().toString());
                                workresource.setWorkSingle(mocta.getTA001());
                                workresource.setWorkNo(mocta.getTA025().trim() + "-" + mocta.getTA006().trim());
                                workresource.setProcessNo(sfcta.getTA003());
                                workresource.setProcessId(sfcta.getTA004());
                                workresource.setResourceGroupId(productprocessresource.getResourceGroupId());

                                if(productprocessresource.getResourceTypeId().equals(1) || productprocessresource.getResourceTypeId().equals(2)) {
                                    List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), mocta.getTA021());
                                    if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                        workresource.setResourceId(idList.get(0));
                                    }
                                }else{
                                    List<Integer> idList = resourceMapper.getResourceIdByTY(productprocessresource.getResourceGroupId(), null);
                                    if(idList != null && idList.size() == 1) {  // 如果末级资源过滤之后，只剩下一个。则直接添加 (直接通过工作中心，过滤)
                                        workresource.setResourceId(idList.get(0));
                                    }
                                }
                                workresource.setDate(TimeUtils.addOrSubtract(mocta.getTA009().trim(), i));
                                workresource.setBeat(productprocessresource.getBeat());
                                workresource.setQuota(productprocessresource.getQuota());
                                workresource.setCreator("ERP");
                                workresource.setCreateTime(TimeUtils.getFullNowTime());
                                workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
                                workresource.setPeopleNum(1);
                                workresource.setResourceTypeId(productprocessresource.getResourceTypeId());
                                workresourceService.save(workresource);
                            }
                        }
                    }
                }
            }


            // Set<String> originSet, Set<String> viewSet, Map<String, HzMoctaView> viewMap, Map<String, String> cmsmvMap, Map<String, BigDecimal> hzCmsmxMap
//            mocta2Service.moctaUpdateOne(originSet, viewSet, viewMap, cmsmvMap, hzCmsmxMap);

//            mocta2Service.saveBatch(insMoctaList);
//            moctyService.saveBatch(insMoctyList);
//            workresourceService.saveBatch(insWorkresourceList);
            // 批量更新

            if(moctaLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTA");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTA"));
            }
        }
        System.out.println("原MOCTA end....." + TimeUtils.getFullNowTime());

        System.out.println("active = " + active);
        if(!"hz".equals(active)) {
            return;
        }
        System.out.println("合并的工单MOCTAMERGE Sync....." + TimeUtils.getFullNowTime());
        Tablesynclog moctaMergeLog = tablesynclogService.getOne(new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTAMERGE"));
        List<HzMoctaView> viewList = null;
        if(moctaMergeLog == null || StringUtils.isEmpty(moctaMergeLog.getLastsynctime())) {   // 如果没记录，则是第一次同步
            viewList = hzViewSyncMapper.hzMoctaMergeViewList(null);
        }else{
            viewList = hzViewSyncMapper.hzMoctaMergeViewList(moctaMergeLog.getLastsynctime());
        }
        if(viewList != null && viewList.size() > 0) {
            List<Cmsmv> cmsmvList = cmsmvMapper.selectList(null);
            Map<String, String> cmsmvMap = new HashMap<>();
            for(Cmsmv cmsmv : cmsmvList) {
                cmsmvMap.put(cmsmv.getMv002().trim(), cmsmv.getMv001().trim());
            }

            List<String> moctaKeyList = moctaMapper.getmoctaKeyList();
            Set<String> originSet = new HashSet<>();
            for(String t : moctaKeyList) originSet.add(t);

            Set<String> viewSet = new HashSet<>();
            Map<String, HzMoctaView> viewMap = new HashMap<>();
            String lastTime = "";
            for(int i = 0; i < viewList.size(); i++) {
                viewList.set(i, LanguageConversionUtils.convertToSimplifiedChinese(viewList.get(i)));
            }
            for(HzMoctaView item : viewList) {
                viewMap.put(item.getTA001().trim() + "^" + item.getTA002().trim(), item);
                viewSet.add(item.getTA001().trim() + "^" + item.getTA002().trim());
                if(lastTime == "") lastTime = item.getModified_time();
                else {
                    if(lastTime.compareTo(item.getModified_time()) < 0) {
                        lastTime = item.getModified_time();
                    }
                }
            }
            Set<String> cp = new HashSet<>(viewSet);
            cp.removeAll(originSet);

            List<MOCTA> insMoctaList = new ArrayList<>();
            List<Mocty> mocties = new ArrayList<>();
            List<Workresource> workresources = new ArrayList<>();
            for(String t : cp) {  // 插入VIEW中多的
                HzMoctaView view = viewMap.get(t);
                MOCTA mocta = new MOCTA();
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setCREATOR("ERP");
                mocta.setCREATE_DATE(TimeUtils.getNowTime());
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                mocta.setUDF51(new BigDecimal(view.getOp_seq()));
                mocta.setUDF52(new BigDecimal(view.getToop_seq()));
                insMoctaList.add(mocta);

                // 隨便去mocty中抓一個
                Mocty pp = moctyMapper.oneMocty(view.getTA001(), view.getTA002());
                if(pp == null) {
                    log.info("1123: " + view.getTA001() + "*" +view.getTA002());
                }
                Mocty mocty2 = new Mocty();
                mocty2.setTy001(view.getTA001().trim());
                mocty2.setTy002(view.getTA002().trim());
                mocty2.setTy003(mocty2.getTy001() + mocty2.getTy002());   // 区分是哪个
                mocty2.setTy004(view.getTA015().doubleValue());
                mocty2.setTy009(pp.getTy009());
                mocty2.setTy019(pp.getTy019());
                mocty2.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
                mocty2.setUdf11(mocty2.getTy001());
                mocty2.setUdf12(mocty2.getTy002());
                mocty2.setUdf05(mocty2.getTy001() + mocty2.getTy002());
                mocties.add(mocty2);

                List<Workresource> list3 = workresourceService.list(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, pp.getUdf05()));
                if(list3 != null && list3.size() > 0) {  // 将WorkResource补录
                    for(Workresource t1 : list3) {
                        Workresource workresource = new Workresource();
                        BeanUtils.copyPropertiesIgnoreCase(t1, workresource);
                        workresource.setWorkResourceId(UUID.randomUUID().toString());
                        workresource.setProductLineId(mocty2.getTy001() + mocty2.getTy002());
                        workresource.setCreateTime(TimeUtils.getFullNowTime());
                        workresources.add(workresource);
                    }
                }

            }

            // 批量插入
            moctaService.saveBatch(insMoctaList);
            moctyService.saveBatch(mocties);
            workresourceService.saveBatch(workresources);
            // 批量更新
            cp = new HashSet<>(originSet);
            cp.retainAll(viewSet);
            for(String t : cp) {
                MOCTA mocta = new MOCTA();
                HzMoctaView view = viewMap.get(t);
                BeanUtils.copyPropertiesIgnoreCase(view, mocta);
                mocta.setUDF01(view.getInvrt_name());  //
                mocta.setUDF02(view.getProcessroute()); //
                mocta.setUDF03(view.getProcessid());   // 工艺ID
                mocta.setUDF04(view.getInv_no());   // 产成品品号
                mocta.setUDF05(view.getSoDue_Date());  // 订单交货日期
                mocta.setUDF06(view.getCustomName());
                mocta.setUDF51(new BigDecimal(view.getOp_seq()));
                mocta.setUDF52(new BigDecimal(view.getToop_seq()));
                String s = cmsmvMap.get(mocta.getTA041());
                if(s != null) mocta.setTA041(s);
                mocta.setMODIFIER("ERP");
                mocta.setMODI_DATE(TimeUtils.getNowTime());
                moctaService.update(mocta, new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, view.getTA001()).eq(MOCTA::getTA002, view.getTA002()));

                Mocty mocty = new Mocty();
                mocty.setTy004(mocta.getTA015().doubleValue());
                moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, view.getTA001().trim() + view.getTA002().trim()));
            }
            if(moctaMergeLog == null) {
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclog.setTablename("MOCTAMERGE");
                tablesynclogService.save(tablesynclog);
            }else{
                Tablesynclog tablesynclog = new Tablesynclog();
                tablesynclog.setLastsynctime(lastTime);
                tablesynclogService.update(tablesynclog, new LambdaQueryWrapper<Tablesynclog>().eq(Tablesynclog::getTablename, "MOCTAMERGE"));
            }
        }
        System.out.println("合并的工单 end....." + TimeUtils.getFullNowTime());

    }

}
